/*
 * @Author: your name
 * @Date: 2019-12-02 11:17:01
 * @LastEditTime: 2022-10-20 14:53:29
 * @LastEditors: ckk
 * @Description: In User Settings Edit
 * @FilePath: \user-center\src\utils\index.js
 */
// const util = require('util')
export function debounce (fn, delay = 500) {
  let timer = null;
  return async function () {
    if (timer) {
      clearTimeout(timer);
    }
    await new Promise((resolve, reject) => {
      timer = setTimeout(() => {
        resolve();
      }, delay);
    });
    // let setTimeout_ = util.promisify(setTimeout)
    // console.log('setTimeout_', setTimeout_)
    // await setTimeout_(1000)
    const flag = await fn.call(this, ...arguments);
    timer = null;
    return flag;
  };
}

/**
 * 打开新窗口
 * @param {string} url
 */
export function openWindow (url) {
  const $link = document.createElement('a');
  $link.href = url;
  $link.setAttribute('target', '_blank');
  document.body.appendChild($link);
  $link.click();
  document.body.removeChild($link);
}

export function getaccessToken () {
  try {
    return JSON.parse(decodeURIComponent(localStorage.getItem('auth_token'))).access_token || '';
  } catch (err) {
    return '';
  }
}

export function printImage (image) {
  const canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;
  const context = canvas.getContext('2d');
  context.drawImage(image, 0, 0, image.width, image.height);

  const newWindow = window.open();
  newWindow.document.write(`<img src="${canvas.toDataURL('image/png')}" />`);
  newWindow.document.close();

  const _timer = window.setTimeout(() => {
    newWindow.print();
    newWindow.close();
    window.clearTimeout(_timer);
  }, 500);
}

export function resizeBase64Image (str, { width, height } = { width: 200, height: 300 }) {
  const image = new Image();
  image.src = str;

  return new Promise((resolve) => {
    image.onload = function () {
      const canvas = document.createElement('canvas'),
        context = canvas.getContext('2d');

      canvas.width = width;
      canvas.height = height;

      context.drawImage(image, 0, 0, width, height);
      resolve(canvas.toDataURL('image/png'));
    };
  });
}

/**
 * 获取屏幕宽高
 */
export function getViewportSize () {
  return {
    width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
    height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  };
}

export function getMobileUrl (row) {
  let mobileUrl = '';
  if (row.mobileUrl && row.mobileUrl !== '') {
    const regExp = new RegExp('\\?', 'g'),
      regExp1 = new RegExp('\\=', 'g'),
      regExp2 = new RegExp('\\/', 'g'),
      regExp3 = new RegExp('\\&', 'g'),
      a = row.mobileUrl.replace(regExp, '>'),
      b = a.replace(regExp1, '<'),
      c = b.replace(regExp2, '(');
    mobileUrl = c.replace(regExp3, '^');
  }
  return encodeURIComponent(mobileUrl);
}

/**
 * 指令指示用户代理将所有站点的不安全URL（通过HTTP提供的URL）视为已被替换为安全URL（通过HTTPS提供的URL）。此指令适用于需要重写大量不安全的旧版URL的网站。
 */
export function set_content_security_policy () {
  if (window.location.protocol === 'http:') return;

  var metas = document.getElementsByTagName('meta'),
    has_set = false;
  for (var i = 0; i < metas.length; i++) {
    if (
      metas[i].getAttributeNode('http-equiv') != null &&
      metas[i].getAttributeNode('http-equiv').value === 'Content-Security-Policy' &&
      metas[i].getAttributeNode('content') != null &&
      metas[i].getAttributeNode('content').value === 'upgrade-insecure-requests'
    ) {
      has_set = true;
      break;
    }
  }
  if (!has_set) {
    var meta_new = document.createElement('META'),
      http_equiv = document.createAttribute('http-equiv'),
      content = document.createAttribute('content');
    http_equiv.value = 'Content-Security-Policy';
    content.value = 'upgrade-insecure-requests';
    meta_new.setAttributeNode(http_equiv);
    meta_new.setAttributeNode(content);
    document.getElementsByTagName('head')[0].appendChild(meta_new);
  }
}

// 向 head 中添加 script
export function addScriptToHead (href = '', fn) {
  const iconLink = document.createElement('script');
  iconLink.type = 'text/javascript';
  const originHost =
    localStorage.getItem('loginData') && JSON.parse(localStorage.getItem('loginData')).NATIONAL_PORTAL_Domain;
  iconLink.src = originHost && `${originHost}/${href}?v=${Date.now()}`;
  iconLink.onload = () => fn();

  // document.head.append(iconLink)
  document.getElementsByTagName('body')[0].appendChild(iconLink);
}

/**
* @Desc 获取域名
* @Author hjp
*/
export function getHost () {
  let hostName = location.host;
  if (hostName.split(':').length > 1) {
    hostName = hostName.split(':')[0];
  }
  return hostName;
}

/**
 * 根据域名获取 拼接对应的播放地址
 */
 export function jointPlayDomain (url, playUrlFlag) {
  const local = localStorage.getItem('loginDataMobile') ? JSON.parse(localStorage.getItem('loginDataMobile')) : {};
  let dUrl = url;
  switch (playUrlFlag) {
    case 0:
      break;
    case 1:
      dUrl = `${local.play_sysvodd_url}${url}`;
      break;
    case 2:
      dUrl = `${local.NATIONAL_PORTAL_Domain}${url}`;
      break;
    case 3:
      dUrl = `${local.play_localvodd_url}${url}`;
      break;
    case 4:
      dUrl = `${window.location.origin}${url}`;
      break;
    default:
      break;
  }
  console.log('local', local, 'dUrl-----', dUrl);
  return dUrl;
}
/**
 * @name getAuthTokenUserInfo
 * @desc 根据token拿取用户基本信息-组织机构id获取
 * @author mhy
 * @Date 2022-09-14 16:23:40
 **/
 export const getAuthTokenUserInfo = () => {
  if (sessionStorage.getItem('air_class_userinfo')) {
    return JSON.parse(sessionStorage.getItem('air_class_userinfo'));
  } else {
    const authToken = localStorage.getItem('auth_token')
      ? JSON.parse(decodeURIComponent(localStorage.getItem('auth_token')))
      : {};
    if (authToken) {
      if (authToken.userinfo && authToken.userinfo.orgId) {
        sessionStorage.setItem('air_class_userinfo', JSON.stringify(authToken.userinfo));
      }
      return (authToken.userinfo || {});
    } else {
      return '';
    }
  }
};
